﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Deployment.Application;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace yichu_front
{
    public partial class Form_Login : Form
    {
        public Form_Login()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string userName = this.txt_userName.Text.Trim();
            ////读取MAC地址
            //string mac = Pub.GetMacAddressByNetworkInformation();
            ////MD5 MAC地址
            //string MD5MAC = Util.MySecurity.GetMD5(mac);
            //密码
            string passWord = this.txt_passWord.Text.Trim();
            string md5passWord = Util.MySecurity.GetMD5(passWord);

            //验证用户名密码MAC是否一致
            User user = SqlSugarHelp.scope.Queryable<User>().Where(it => it.账号 == userName && it.MD5密码 == md5passWord).First();
            if (user != null)
            {
                // 检查是否记住密码，记住则保存
                if (this.checkBoxRememberMe.Checked)
                {
                    Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    cfa.AppSettings.Settings["rememberMe"].Value = "true";
                    cfa.AppSettings.Settings["userName"].Value = txt_userName.Text.Trim(); // 账号（默认记住）
                    cfa.AppSettings.Settings["passWord"].Value = txt_passWord.Text.Trim(); // 密码
                    cfa.Save();
                }
                else
                {
                    Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    cfa.AppSettings.Settings["rememberMe"].Value = "";
                    cfa.AppSettings.Settings["userName"].Value = ""; // 账号（默认记住）
                    cfa.AppSettings.Settings["passWord"].Value = ""; // 密码
                    cfa.Save();
                }
                //存在，则打开主页面
                Pub.username = userName;
                Pub.user = user;
                Form_Notice form_Notice = new Form_Notice();
                form_Notice.Show();
                this.Hide();
            }
            else
            {
                //不存在，不做动作
            }
        }

        private void Form_Login_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void Form_Login_Shown(object sender, EventArgs e)
        {
            //if (ConfigurationManager.AppSettings[name: "rememberMe"].Equals("true"))
            //{
            //    this.txt_userName.Text = ConfigurationManager.AppSettings["userName"];
            //    this.txt_passWord.Text = ConfigurationManager.AppSettings["passWord"];
            //    checkBoxRememberMe.Checked = true;
            //}
        }

        private void Form_Login_Load(object sender, EventArgs e)
        {
            //检查更新
            string oldversion = GetVersion();
            label4.Text = oldversion;
            //获取程序名
            string appName = Application.ProductName;
            string sql = $"select 版本号,url from AppVersion where 程序类型 = '{appName}'";
            DataTable version = SqlSugarHelp.scope.Ado.GetDataTable(sql);
            if (oldversion != version.Rows[0][0].ToString())
            {
                //提示有更新要求升级
                DialogResult dialogResult = MessageBox.Show($"有新版本是否更新。当前版本{oldversion},新版本{version.Rows[0][0].ToString()}", "提示", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    更新(version.Rows[0][1].ToString(),appName);
                }
                else
                {
                    Application.Exit();
                }
            }
        }

        public string GetVersion()
        {
            //注意在调试的时候是获取不到版本号的，需要程序发布之后才能获得
            return ApplicationDeployment.IsNetworkDeployed
            ? ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString()
            : System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
        }
        private void 更新(string url,string appName)
        {
            //运行当前目录的上级目录里的 合同管理下载更新.exe 程序
            string applicationPath = Application.StartupPath;
            applicationPath = Path.GetFullPath("..");
            string consoleAppPath = Path.Combine(applicationPath, "下载更新.exe");
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = consoleAppPath;
            startInfo.Arguments = $"{url}"+" "+$"{appName}";
            Process.Start(startInfo);
            // 结束当前 WinForms 进程
            Application.Exit();
        }
    }
}
